// pages/nurse/publishvideo/publishvideo.js
var api = require('../../../config/api.js')

const uploadImage = require('../../../oss-upload/uploadAliyun.js');

var uploadAliyun = require('../../../oss-upload/uploadAliyun.js');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    disabled: false,
    // 标题数
    titleCount: 0,
    title: '',
    video : '',
    id : -1,
    url : '',
    Item: [
      {value: 0, name: '维护知识', checked: true},
      {value: 1, name: '健康知识', checked: false},
    ],
    type: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  // 上传视频
  chooseVideo() {
    // 弹层  
    wx.showToast({
      title: '只能选择视频类型上传!',
      icon: 'none',
      duration: 2000,
      success: res => {
        wx.chooseVideo({
          sourceType: ['album', 'camera'],
          compressed: true,
          maxDuration: 10,
          camera: 'back',
          success: res => {
            console.log(res);
            const video = res.tempFilePath;
            this.setData({video})
          }
        })
      }
    })
  },
  // 删除视频
  videoDelete(){
    wx.showModal({
      title: '警告',
      content: '确定要删除该视频吗',
      success: res => {
        if (res.confirm) {
          this.setData({
            video: ''
          })
        }
      }
    })
  },
// 表单提交事件
submitClick() {
  let that = this;
  that.setData({
    disabled: true
  });
  console.log("title count" + that.data.titleCount);
  console.log("video" + that.data.video);
  if(that.data.titleCount == 0) {
    wx.showModal({
      title: '警告',
      content: '请输入标题'
    })
    return;
  }
  if(that.data.video == '') {
    wx.showModal({
      title: '警告',
      content: '请选择需要上传的视频文件'
    })
    return;
  }

  //filePath为要上传的本地文件的路径
  //images/为oss目录
  wx.showLoading({
    title: '上传中',
  })

  that.uploadVideo(that.data.video, that.data.title).then(function(res){
    console.log('uploadVideo res = ' + res);
    if(res){
      that.setData({
        id: res.id,
        url: res.url
      });

      that.sendArticelToServer();
    }
  });
},

uploadVideo: function(videoSrc, title) {
  return new Promise(function (resolve, reject) {

    const aliyunFileKey = 'images/' + (new Date().getTime()) + '.mp4';
    const aliyunServerURL = api.videoUpload;
    const accessid = api.accessid;
    const policyBase64 = uploadAliyun.getPolicyBase64();
    const signature = uploadAliyun.getSignature(policyBase64);

    console.log('aliyunFileKey=', aliyunFileKey);

    const uploadTask = wx.uploadFile({
      url: aliyunServerURL, //仅为示例，非真实的接口地址
      filePath: videoSrc,
      name: 'file',
      formData: {
          'key': aliyunFileKey,
          'OSSAccessKeyId': accessid,
          'policy': policyBase64,
          'Signature': signature,
          'success_action_status': '200',
      },
      success (res){
        var data;
        console.log("upload video: res = " + JSON.stringify(res));

        var info_temp = {
          url: 'https://bitfun.site/' + aliyunFileKey,
          id: 0
        }
        if (res.statusCode == 200) {
          resolve(info_temp);
        } else {
          reject(res.statusCode);
          wx.hideLoading()
          wx.showModal({
            title: '上传失败请稍后重试...',
            content: '失败',
            showCancel: false
          });
        }
      }
    })
    
    uploadTask.onProgressUpdate((res) => {
      wx.showLoading({
        title: '上传中',
      })
      /*setTimeout(function () {
        wx.hideLoading()
      }, 2000)*/
      
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    })
  });
},

sendArticelToServer: function(wxCode) {
  let that = this;

  console.log('sendArticelToServer = id ' + that.data.id
        + 'url ' + that.data.url);

  wx.request({
    url: api.uploadArticel,
    data: {
      headerId: that.data.id,
      name: that.data.title,
      categoryId: that.data.type,
      detailUrl: that.data.url
    },
    method: 'POST',
    header: {
      'content-type': 'application/json'
    },
    success: function(res) {
      console.log('sendArticelToServer res.data = ' + JSON.stringify(res.data));

      wx.hideLoading()

      if (res.data.errno == 0) {

        wx.showModal({
          title: '视频已上传',
          content: res.data.errmsg,
          showCancel: false,
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateBack();
            } else if (res.cancel) {
              console.log('用户点击取消')
              wx.navigateBack();
            }
          }
        });
      } else {
        wx.showModal({
          title: '错误信息',
          showCancel: false
        });
      }
    }
  });
},

// 重置表单
resetClick() {
  wx.showModal({
    title: '警告',
    content: '重置后将需要重新上传数据',
    success: res => {
      if (res.confirm) {
        this.setData({
          title: '',
          video : ''
        })
      }
    }
  })
},
  // 标题操作
  handleTitleInput(event) {
    let inputValue = event.detail.value;
    // 确保标题不存在空格  
    if(inputValue.lastIndexOf(" ") != -1){
      inputValue = inputValue.substring(0, inputValue.lastIndexOf(" "));
    }
    let titleCount = inputValue.length;
    if(titleCount <= 25){
      this.setData({
        titleCount: titleCount ,
        title: inputValue
      })
    }
  },
  radioChange(e) {
    console.log('radioChange发生change事件，携带value值为：', e.detail.value)

    const Item = this.data.Item
    for (let i = 0, len = Item.length; i < len; ++i) {
      console.log('radioChange发生change事件，Item[i].value ', Item[i].value)
      Item[i].checked = Item[i].value == e.detail.value
      console.log('radioChange发生change事件，Item[i].checked值为：', Item[i].checked)
    }

    this.setData({
      Item
    })

    for (let i = 0, len = Item.length; i < len; ++i) {
      console.log('RadioChange发生change事件，sexItem[i].checked值为：', Item[i].checked)
      if(Item[i].checked) {
          this.setData({
            type: Item[i].value
          })
      }
    }
  },

})